package main.java.com.fileUpload.controller;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/file")
public class FileUploadController {
	
	@RequestMapping("/one/upload.do")
	public ModelAndView fileUpload(@RequestParam("file")CommonsMultipartFile file){
		return new ModelAndView("index");
	}
	
	@RequestMapping("/upload.do")
	public String fileUpload(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{
		ServletContext servletContext = request.getSession().getServletContext();
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(servletContext);
		if(commonsMultipartResolver.isMultipart(request)){
			MultipartHttpServletRequest resolveMultipart = commonsMultipartResolver.resolveMultipart(request);
			Iterator<String> fileNames = resolveMultipart.getFileNames();
			while (fileNames.hasNext()) {
				String fileName = (String) fileNames.next();
				MultipartFile file = resolveMultipart.getFile(fileName);
				if(file != null){
					String newFileName = file.getOriginalFilename();
					String realPath = servletContext.getRealPath("/");
//					String basePath = request.getContextPath();
//					String path = basePath+"/"+servletContext.getContextPath()+"\\upload\"+newFileName;
					String path = realPath+"\\upload\\"+newFileName;
					File newFile = new File(path);
					file.transferTo(newFile);
				}
			}
		}
		return "fileUpload/fileUploadSuccess";
	}
}
